package com.xg.sys.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xg.sys.entity.SysDictionary;
import com.xg.sys.entity.SysMenu;
import com.xg.sys.entity.SysUser;
import com.xg.sys.mapper.MenuBeanMapper;
import com.xg.sys.mapper.SysMenuMapper;
import com.xg.sys.service.SysDictionaryService;
import com.xg.sys.service.SysMenuService;
import com.xg.sys.vo.SelectVO;
import com.xg.sys.vo.SysMenuVO;
import com.xg.sys.vo.TreeVO;
import com.xg.utils.DDDUtils;
import com.xg.frame.constant.Constant;
import com.xg.frame.constant.SysConstant;
import io.jsonwebtoken.lang.Collections;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author dehuisun
 * @since 2019-04-10
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    @Autowired
    private MenuBeanMapper menuBeanMapper;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Autowired
    private SysDictionaryService sysDictionaryService;

    private GlobalConfig gc = GlobalConfigUtils.defaults();

    @Override
    public List<SysMenuVO> getCurrentUserMenus(Long userId) {
        List<SysMenu> menuBeans = menuBeanMapper.queryListByUserId(userId, SysConstant.STATUS_Y,
                gc.getDbConfig().getLogicDeleteField(), gc.getDbConfig().getLogicNotDeleteValue());
        //替换字典值为icon
        List<SysDictionary> list = sysDictionaryService.getDiclist("1004");
        JSONObject iconDic = new JSONObject();
  /*      list.forEach(item -> iconDic.put(item.getDataCode(), item.getDataName()));
        menuBeans.forEach(item -> {
            if (iconDic.containsKey(item.getIcon())) {
                item.setIcon(String.valueOf(iconDic.get(item.getIcon())));
            }
        });*/
        List<SysMenuVO> menuVOs = (List) DDDUtils.collection(menuBeans, SysMenuVO.class);
        List<SysMenuVO> results = menuVOs.stream()
                .filter(item -> item.getParentId() == SysConstant.ROOT_PARENT_ID)
                .collect(Collectors.toList());
        results.forEach(item -> getChildMenu(item, menuVOs));
        return results;
    }

    private void getChildMenu(SysMenuVO parentMenu, List<SysMenuVO> menuVOs) {
        List<SysMenuVO> childList = menuVOs.stream().filter(item -> item.getParentId().equals(parentMenu.getId())).collect(Collectors.toList());
        if (!Collections.isEmpty(childList)) {
            parentMenu.setList(childList);
            childList.forEach(item -> getChildMenu(item, menuVOs));
        }
    }

    public List<SysMenu> queryListParentId(Long parentId, List<Long> menuIdList, Long userId) {
        List<SysMenu> menuList = queryListParentId(parentId, userId);
        if (menuIdList == null) {
            return menuList;
        }

        List<SysMenu> userMenuList = new ArrayList<>();
        for (SysMenu menu : menuList) {
            if (menuIdList.contains(menu.getId())) {
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    public List<SysMenu> queryListParentId(Long parentId, Long userId) {
        return menuBeanMapper.queryListParentId(parentId, userId);
    }

    @Override
    public List<SelectVO> getParentMenusForSelect() {
        List<SysMenu> list = this.list(
                new QueryWrapper<SysMenu>().lambda()
                        .select(SysMenu::getId, SysMenu::getName)
                        .eq(SysMenu::getType, Constant.MenuType.CATALOG)
                        .eq(SysMenu::getStatus, SysConstant.STATUS_Y)
                        .orderByAsc(SysMenu::getOrderNum)
        );

        List<SelectVO> selectList = list.stream()
                .map(item -> new SelectVO().setCode(item.getId().toString()).setName(item.getName()))
                .collect(Collectors.toList());

        selectList.add(new SelectVO().setCode("0").setName("根目录"));

        return selectList;
    }

    @Override
    public List<SysMenu> selectSbuMenuOrButton(Long menuId) {//在用
        return sysMenuMapper.selectSbuMenuOrButton(menuId);
    }

    @Override
    public List<TreeVO> treeForYkk() throws NoSuchMethodException {
        //1.查询当前登录用户菜单
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        List<SysMenu> sysMenuList = sysMenuMapper.queryListByUserId(
                user.getId(),
                SysConstant.STATUS_Y,
                gc.getDbConfig().getLogicDeleteField(),
                gc.getDbConfig().getLogicNotDeleteValue());
        //2.实体复制到TreeVO
        return TreeVO.toTree(sysMenuList);
    }

    @Override
    public List<TreeVO> treeAll() throws NoSuchMethodException {
        //1.查询当前登录用户菜单
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        final List<SysMenu> allList = sysMenuMapper.selectList(new LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, SysConstant.STATUS_Y));
        //2.实体复制到TreeVO
        return TreeVO.toTree(allList);
    }

    @Override
    public List<SysMenu> getByParentId(Long id) {
        return this.list(
                new LambdaQueryWrapper<SysMenu>()
                        .eq(SysMenu::getParentId, id)
        );
    }

    @Override
    public List<SysMenu> getByUserId(Long userId) {
        return sysMenuMapper.selectByUserId(userId);
    }

    @Override
    public List<SysMenu> getByRoleId(Long roleId) {
        return sysMenuMapper.getByRoleId(roleId);
    }
}
